package com.elock.intf.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.dao.impl.DaoCenter;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.ExceptionUtil;
import com.elock.entity.Elock;

/**
 * Dao - 锁
 * @author 仁德
 */
@Repository("intfElockDao")
public class IntfElockDao extends DaoCenter {

	public Page<Map<String, Object>> findPage(Pageable pageable, Object[] args) {

		List<Object> list = new ArrayList<Object>();

		String companyCode = (String) args[0];
		String elockNum = (String) args[1];
		String elockName = (String) args[2];
		String saleOrgSn = (String) args[3];
		Boolean isSelect = (Boolean) args[4];

		StringBuilder sql = new StringBuilder();
		sql.append(
				" select e.*,sdt.value type_value,sdm.value model_value,so.name sale_org_name");
		sql.append(" from elock e left join system_dict sdt on e.type=sdt.id");
		sql.append(" left join elock_sale_org eso on e.id=eso.elock");
		sql.append(" left join sale_org so on eso.sale_org=so.id");
		sql.append(" left join company_info c on c.id=e.company_info_id");
		sql.append(" left join system_dict sdm on e.model= sdm.id where 1=1");
		if (companyCode != null) {
			sql.append(" and c.company_code=?");
			list.add(companyCode);
		}
		if (!ConvertUtil.isEmpty(elockNum)) {
			sql.append(" and e.elock_number like ?");
			list.add("%" + elockNum + "%");
		}
		if (!ConvertUtil.isEmpty(elockName)) {
			sql.append(" and c.elock_name like ?");
			list.add("%" + elockName + "%");
		}
		if (saleOrgSn != null) {
			sql.append(" and so.sn=?");
			list.add(saleOrgSn);
		}
		if (isSelect != null && isSelect) {
			sql.append(" and not exists (select 1 from elock_car where elock_id = e.id)");
		}
		sql.append(" order by e.create_date desc");

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}

		Page<Map<String, Object>> getPage = getNativeDao().findPageMap(sql.toString(),
				objs,
				pageable);

		return getPage;

	}

	public Elock findByElockNum(String elockNum) {

		if (ConvertUtil.isEmpty(elockNum)) {
			ExceptionUtil.throwDaoException("value is empty!");
		}
		String sql = "select * from elock where elock_num = ?";
		Elock elock = getNativeDao().findSingleManaged(sql,
				new Object[] { elockNum },
				Elock.class);
		return elock;
	}

}